#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDesktopWidget>
#include <QFileDialog>
#include <QScreen>
#include <QString>
#include <QDebug>
#include <QPoint>
#include <QTime>
#include <QMouseEvent>
#include "screen.h"
#include <QSettings>
#include <QMessageBox>
#include <QDateTime>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QJsonParseError>
#include <QJsonDocument>
#include <QJsonObject>
#include <QTextCodec>
#include <QJsonArray>
#include <QClipboard>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){
    ui->setupUi(this);
    beginPos = this->pos();
    leftPress = false;
    this->setProperty("CanMove", true);
    //实现无边框 (Qt::FramelessWindowHint去边框)  Qt::WindowStaysOnTopHint 窗体置顶 防止拖到任务栏下面
    //this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint|Qt::WindowStaysOnTopHint);
    QSettings *configIniWrite = new QSettings("set.ini", QSettings::IniFormat);
    ui->lineEdit->setText(configIniWrite->value("key").toString());
    ui->lineEdit_2->setText(configIniWrite->value("secret").toString());
    delete configIniWrite;
}

void MainWindow::getNewStr(QString newstr) {
    ui->textEdit->setPlainText(newstr);
    if(ui->checkBox_2->isChecked() == true){
        if(ui->lineEdit->text().isEmpty() || ui->lineEdit_2->text().isEmpty()){
            QMessageBox::information(NULL, "错误", "百度密钥不能为空");
            return;
        }
        getTextByApi();
    }
}

/**
 * @brief MainWindow::on_action_2_triggered
 * 截图
 */
void MainWindow::on_action_2_triggered(){
    //截图之前隐去窗体，不然截图之中就会有窗体的存在
    if(ui->checkBox->isChecked() == true){
        if( windowState() != Qt::WindowMinimized ){
             setWindowState( Qt::WindowMinimized );//最小化父窗体
        }
        //延时等待父窗体最小化 延时250毫秒
        QTime _Timer = QTime::currentTime().addMSecs(250);
        while( QTime::currentTime() < _Timer ){
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
        }
    }
    ui->textEdit->setPlainText("");
    ui->textEdit_2->setPlainText("");
    Screen *m = new Screen();
    QObject::connect(m,SIGNAL(sendNewStr(QString)),this,SLOT(getNewStr(QString)));
    m->fullScreen = QPixmap::grabWindow(QApplication::desktop()->winId());
    m->showFullScreen();

}

void MainWindow::mousePressEvent(QMouseEvent *e){ //--鼠标按下事件
    if (e->button() == Qt::LeftButton){//鼠标左键按下
        leftPress = true;
        beginPos = e->pos();//鼠标相对窗体的位置
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *e){ //--鼠标移动事件
    if (leftPress){//当前鼠标相对窗体的位置-刚按下左键时的相对位置=鼠标移动的大小
         move(e->pos() - beginPos + this->pos()); //鼠标移动的大小+窗体原来的位置=窗体移动后的位置
    }

}

void MainWindow::mouseReleaseEvent(QMouseEvent *e){ //--鼠标释放（松开）事件
    leftPress = false;
}

void MainWindow::enterEvent(QEvent *e){ //--鼠标进入事件
    if(this->pos().y()<=0){//鼠标进入并且已经贴边
        move(pos().x(),0);//弹出整个窗体
    }

}

void MainWindow::leaveEvent(QEvent *e){//--鼠标离开事件
    if(this->pos().y()<=0){//窗体贴在屏幕上边
        move(pos().x(),-29);//贴边
    }
}


MainWindow::~MainWindow(){
    delete ui;
}

/**
 * @brief MainWindow::on_action_triggered
 * 保存百度接口密钥
 */
void MainWindow::on_action_triggered(){
    QString key = ui->lineEdit->text();
    QString secret = ui->lineEdit_2->text();
    QSettings *configIniWrite = new QSettings("set.ini", QSettings::IniFormat);
   //向ini文件中写入内容,setValue函数的两个参数是键值对
   configIniWrite->setValue("key", key);
   configIniWrite->setValue("secret", secret);
   //写入完成后删除指针
   delete configIniWrite;
   QMessageBox::information(NULL, "成功", "保存成功");
}

/**
 * @brief MainWindow::getTextByApi
 * 通过百度api获取图片内容
 */
void MainWindow::getTextByApi(){
    getAccessToken();
    recognition();
}

/**
 * @brief MainWindow::recognition
 * 通用文字识别
 */
void MainWindow::recognition(){
    QString parm = ui->textEdit->toPlainText();
    if(parm.isEmpty()){
        QMessageBox::information(NULL, "错误", "图像数据不能为空");
        return;
    }
    nam = new QNetworkAccessManager(this);
    QUrl url;
    if(ui->checkBox_4->isChecked()){
        url.setUrl("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token="+accessToken);
    }else{
        url.setUrl("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="+accessToken);
    }
    QNetworkRequest request;
    request.setUrl(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/x-www-form-urlencoded"));
    QByteArray byteArr;
    byteArr.append("image=");
    byteArr.append(QUrl::toPercentEncoding(parm));
    connect(nam, &QNetworkAccessManager::finished,this, &MainWindow::recognitionRequestFinished);
    QNetworkReply* reply = nam->post(request,byteArr);
}



/**
 * @brief MainWindow::getAccessToken
 * 获取百度Access Token
 */
void MainWindow::getAccessToken(){
    QString key = ui->lineEdit->text();
    QString secret = ui->lineEdit_2->text();
    QSettings *configIniWrite = new QSettings("set.ini", QSettings::IniFormat);
    QDateTime time = QDateTime::currentDateTime();   //获取当前时间
    int timeT = time.toTime_t();   //将当前时间转为时间戳
    if((configIniWrite->value("tokenTime").toInt() + 30*24*3600) < timeT){
        nam = new QNetworkAccessManager(this);
        QString parm = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+key+"&client_secret="+secret+"&";
        QUrl url(parm);
        connect(nam, &QNetworkAccessManager::finished,this, &MainWindow::getAccessTokenRequestFinished);
        QNetworkReply* reply = nam->get(QNetworkRequest(url));
    }else{
        accessToken = configIniWrite->value("accessToken").toString();
    }
}

/**
 * @brief MainWindow::requestFinished
 * @param reply
 * 获取access_token后的信号槽
 */
void MainWindow::getAccessTokenRequestFinished(QNetworkReply* reply) {
    QNetworkReply::NetworkError err = reply->error();
    if(err != QNetworkReply::NoError) {
        qDebug() << "Failed: " << reply->errorString();
    }else {
        // 获取返回内容
        QJsonParseError json_error;
        QJsonDocument parse_doucment = QJsonDocument::fromJson(reply->readAll(), &json_error);
        if(parse_doucment.isObject()){
             QJsonObject obj = parse_doucment.object();
             accessToken = obj.take("access_token").toString();
             QSettings *configIniWrite = new QSettings("set.ini", QSettings::IniFormat);
            //向ini文件中写入内容,setValue函数的两个参数是键值对
            configIniWrite->setValue("accessToken", accessToken);
            QDateTime time = QDateTime::currentDateTime();   //获取当前时间
            int timeT = time.toTime_t();   //将当前时间转为时间戳
            configIniWrite->setValue("tokenTime", timeT);
            //写入完成后删除指针
            delete configIniWrite;
        }
    }
    nam->deleteLater();
}

/**
 * @brief MainWindow::recognitionRequestFinished
 * @param reply
 * 文字识别的信号槽
 */
void MainWindow::recognitionRequestFinished(QNetworkReply* reply){
    QNetworkReply::NetworkError err = reply->error();
    //qDebug()<<reply->readAll();
    if(err != QNetworkReply::NoError) {
        qDebug() << "Failed: " << reply->errorString();
    }else {
        // 获取返回内容
        QJsonParseError json_error;
        QJsonDocument parse_doucment = QJsonDocument::fromJson(reply->readAll(), &json_error);
        if(parse_doucment.isObject()){
            QJsonObject obj = parse_doucment.object();
            int wordsNum = obj.take("words_result_num").toInt();
            if(wordsNum > 0){
                QString res;
                QJsonArray jsonArr = obj.take("words_result").toArray();
                for(int i=0;i<wordsNum;i++){
                   res.append(jsonArr[i].toObject().take("words").toString());
                   res.append("<br>");
                }
                ui->textEdit_2->setText(res);
                if(!res.isEmpty()&&ui->checkBox_3->isChecked()){
                    QClipboard *board = QApplication::clipboard();
                    board->setText(res);
                }
            }else{
                QMessageBox::information(NULL, "提示", "无法识别图片内容");
            }
        }
    }
    nam->deleteLater();
}
/**
 * @brief MainWindow::on_action_3_triggered
 * 识别按钮
 */
void MainWindow::on_action_3_triggered(){
    if(ui->lineEdit->text().isEmpty() || ui->lineEdit_2->text().isEmpty()){
        QMessageBox::information(NULL, "错误", "百度密钥不能为空");
        return;
    }
    getTextByApi();
}
/**
 * @brief MainWindow::on_action_4_triggered
 * 复制
 */
void MainWindow::on_action_4_triggered(){
    QClipboard *board = QApplication::clipboard();
    board->setText(ui->textEdit_2->toPlainText());
}
